import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Alert, Form, Switch, Icon, Input, Select, Button, Row, Col, message, InputNumber, Popover, Tooltip } from 'antd'
import Chooser from 'components/chooser'
import Searcher from 'components/searcher'
import searcherData from 'share/searcherData'
const FormItem = Form.Item;
const Option = Select.Option;
const TextArea = Input.TextArea;
import creditModelService from 'containers/credit-setting/credit-model/credit-model.service'
import constants from 'share/constants'
import config from 'config'
import errorMessage from 'share/errorMessage'

class NewCreditModelRule extends React.Component {
  constructor(props) {
    super(props);
    this.replySelectorItem = {
      title: messages('credit-setting.key71')/*选择意见*/,
      url: `${config.baseUrl}/api/credit/${this.props.params.setId}/reply`,
      searchForm: [{
        type: 'input', id: 'reply', label: messages('credit-setting.key72')/*意见内容*/
      },{
        type: 'select', id: 'replyType', label: messages('credit-setting.key73')/*意见类型*/,
        options: [{ label: messages('credit-setting.key74')/*审批*/, value: 1001 },{ label: messages('credit-setting.key75')/*审核*/, value: 1002 }]
      }],
      columns: [{
        title: messages('credit-setting.key76')/*意见*/, dataIndex: 'reply', render: text => <span>{text ? <Popover placement="topLeft" content={text} overlayStyle={{maxWidth: 400}}>{text}</Popover> : '-'}</span>
      },{
        title: messages('credit-setting.key73')/*意见类型*/, dataIndex: 'replyType', render: replyType => replyType === 1001 ? messages('credit-setting.key74')/*审批*/ : messages('credit-setting.key75')/*审核*/
      }],
      key: "id"
    };
    this.state = {
      loading: false,
      data: {}
    };
  }

  onCancel = () => {
    this.props.close();
  };

  componentWillReceiveProps(nextProps){
    if(nextProps.params.showSlideFrame && !this.props.params.showSlideFrame){
      let nextData = nextProps.params.nowData;
      let ruleTypeId = nextProps.params.ruleTypeId;
      if(!nextData.id){
        this.props.form.resetFields();
      } else {
        let valueWillSet = this.props.form.getFieldsValue();
        Object.keys(valueWillSet).map(key => {
          valueWillSet[key] = nextData[key];
          if(key === 'creditRelationDTOList' && ruleTypeId !== 1001){ //自动信用没有关联意见
            valueWillSet[key].map(item => {
              item.id = item.replyId;
            })
          }
          if(key === 'ruleConditionAuto' && (ruleTypeId === 1001 || ruleTypeId === 1003)){ //自动信用
            valueWillSet[key] = [
              {
                conditionName: nextData['ruleCondition'],
                conditionCode: nextData['ruleConditionCode']
              }
            ];
          }
        });
        this.props.form.setFieldsValue(valueWillSet);
        switch(valueWillSet.operationType){
          case(1001):
            valueWillSet = { changeScore: nextData.changeScore };
            break;
          case(1002):
            valueWillSet = { changeScore: -nextData.changeScore };
            break;
          case(1003):
            valueWillSet = { changeRank: nextData.changeRank };
            break;
          case(1004):
            valueWillSet = { changeRank: -nextData.changeRank };
        }
        setTimeout(() => {
          this.props.form.setFieldsValue(valueWillSet);
        }, 0);
      }
    }
  }

  handleSave = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { nowData, setId, ruleTypeId } = this.props.params;
        const { creditModel } = this.props;
        if(nowData.id){
          values = Object.assign(nowData, values);
        }
        if (ruleTypeId === 1001) {
          values.ruleCondition = values.ruleConditionAuto[0].conditionName;
        }
        values.ruleSetId = setId;
        ruleTypeId === 1002 && values.creditRelationDTOList && values.creditRelationDTOList.map(item => {
          item.modelId = creditModel.id;
          item.replyId = item.id;
        });
        if(values.operationType === 1002){
          values.changeScore = -values.changeScore
        }
        if(values.operationType === 1004){
          values.changeRank = -values.changeRank
        }
        if (ruleTypeId === 1003) {
          values.ruleCondition = values.ruleConditionAuto[0].conditionName;
          values.type = values.ruleConditionAuto[0].conditionType;
        }
        this.setState({ loading: true });
        creditModelService.saveCreditRule(setId, values).then(res => {
          this.setState({ loading: false });
          message.success(messages('credit-setting.key45')/*保存成功*/);
          this.props.close(true);
        }).catch(e => {
          errorMessage(e.response);
          this.setState({ loading: false });
        })
      }
    });
  };

  renderChange = () => {
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 10, offset: 1 },
    };
    const { getFieldDecorator, getFieldValue } = this.props.form;
    let operationType = getFieldValue('operationType');
    switch(operationType){
      case 1001:
        return (
          <FormItem {...formItemLayout} label={messages('credit-setting.key77')/*分值*/}>
            {getFieldDecorator('changeScore', {
              rules: [
                {
                  required: true,
                  message: messages('common.please.enter')
                },
                {
                  validator: (item, value, callback) => {
                    if(value < 0){
                      callback(messages('credit-setting.key78')/*请输入正数！*/)
                    }
                    if(value === 0){
                      callback(messages('credit-setting.key78')/*请输入正数！*/)
                    }
                    if (value && isNaN(value) && value !== 0 && value !== '') {
                      callback(messages('credit-setting.key78')/*请输入正数！*/)
                    }
                    callback();
                  }
                }
              ]
            })(
              <InputNumber min={0} precision={1}/>
            )}
          </FormItem>
        );
      case 1002:
        return (
          <FormItem {...formItemLayout} label={messages('credit-setting.key77')/*分值*/}>
            {getFieldDecorator('changeScore', {
              normalize: value => {
                if(value === 0)
                  return '-0';
                return value;
              },
              rules: [
                {
                  required: true,
                  message: messages('common.please.enter')
                },
                {
                  validator: (item, value, callback) => {
                    if(value > 0){
                      callback(messages('credit-setting.key79')/*请输入负数！*/)
                    }
                    if(value && isNaN(value) && value !== 0 && value !== ''){
                      callback(messages('credit-setting.key79')/*请输入负数！*/)
                    }
                    callback();
                  }
                }
              ]
            })(
              <InputNumber max={0} precision={1}/>
            )}
          </FormItem>
        );
      case 1003:
        return <FormItem {...formItemLayout} label={messages('credit-setting.key80')/*极差*/}>
          {getFieldDecorator('changeRank', {
            rules: [
              {
                required: true,
                message: messages('common.please.enter')
              },
              {
                validator: (item, value, callback) => {
                  if(value < 0){
                    callback(messages('credit-setting.key81')/*请输入正整数*/)
                  }
                  if(value === 0){
                    callback(messages('credit-setting.key81')/*请输入正整数*/)
                  }
                  if(value && isNaN(value) && value !== 0 && value !== ''){
                    callback(messages('credit-setting.key81')/*请输入正整数*/)
                  }
                  callback();
                }
              }
            ]
          })(
            <InputNumber min={0} precision={0}/>
          )}
        </FormItem>
      case 1004:
        return <FormItem {...formItemLayout} label={messages('credit-setting.key80')/*极差*/}>
          {getFieldDecorator('changeRank', {
            rules: [
              {
                required: true,
                message: messages('common.please.enter')
              },
              {
                validator: (item, value, callback) => {
                  if(value > 0){
                    callback(messages('credit-setting.key82')/*请输入负整数*/)
                  }
                  if(value === 0){
                    callback(messages('credit-setting.key82')/*请输入负整数*/)
                  }
                  if(value && isNaN(value) && value !== 0 && value !== ''){
                    callback(messages('credit-setting.key82')/*请输入负整数*/)
                  }
                  callback();
                }
              }
            ]
          })(
            <InputNumber max={0} precision={0}/>
          )}
        </FormItem>
    }
  };

  handleChangeOperationType = type => {
    this.props.form.setFieldsValue({ [type > 1002 ? 'changeRank' : 'changeScore']: null })
  };

  handleConditionChange = (values) => {
    const { setFieldsValue } = this.props.form;
    if (values && values.length) {
      setFieldsValue({
        'ruleConditionCode': values[0].conditionCode,
        'comment': values[0].comment,
        'type': values[0].conditionType,
      });
    }
    if (!values.length) {
      setFieldsValue({'ruleConditionCode': undefined, 'comment': undefined});
    }
  };

  render(){
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { loading } = this.state;
    const { nowData, ruleTypeId, setId } = this.props.params;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 10, offset: 1 },
    };
    let searcherItem = JSON.parse(JSON.stringify(searcherData['auto_credit_rule']));
    searcherItem.url = searcherItem.url.replace('{ruleSetId}', setId);
    return (
      <div>
        <Alert
          message={messages('common.help')/*提示信息*/}
          description={messages('credit-setting.key83')/*升级/降级，将会将信用分值直接变为目标等级的最低分。*/}
          type="info"
          showIcon
        />
        <Form onSubmit={this.handleSave} style={{ marginTop: 30 }}>
          {(ruleTypeId === 1001 || ruleTypeId === 1003) && (
            <FormItem {...formItemLayout} label={messages('credit-setting.key39')/*规则项*/}>
              {getFieldDecorator('ruleConditionAuto', {
                rules: [
                  {
                    required: true,
                    message: messages('common.please.select')
                  },
                ]
              })(
                <Searcher type="auto_credit_rule"
                          searcherItem={searcherItem}
                          labelKey="conditionName"
                          descriptionKey={record => `${record.conditionCode} ${record.comment}`}
                          disabled={!!nowData.id}
                          placeholder=""
                          showClear={false}
                          single
                          onChange={values => this.handleConditionChange(values)}/>
              )}
            </FormItem>
          )}
          {ruleTypeId === 1002 && (
            <FormItem {...formItemLayout} label={messages('credit-setting.key39')/*规则项*/}>
              {getFieldDecorator('ruleCondition', {
                rules: [
                  {
                    required: true,
                    message: messages('common.please.select')
                  },
                ]
              })(
                <Input maxLength="200"/>
              )}
            </FormItem>
          )}
          {ruleTypeId === 1001 && (getFieldValue('ruleConditionCode') === 'SWEEP_RECEIVE' || getFieldValue('ruleConditionCode') === 'EXPENSE_SUBMIT') && (
            <div>
              <FormItem {...formItemLayout} label={messages('credit-setting.key114')/*判断逻辑*/}>
                {getFieldDecorator('operator', {
                  rules: [
                    {
                      required: true,
                      message: messages('common.please.select')
                    },
                  ],
                  initialValue: nowData.id ? nowData['operator'] : undefined
                })(
                  <Select>
                    {constants.creditRuleOperator
                      .map(item => <Option
                        key={item.value}
                        value={item.value}>{item.name}</Option>)}
                  </Select>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label={(
                <span>{messages('credit-setting.key115')/*期限天数*/}&nbsp;
                  <Tooltip title={messages('credit-setting.key81')/*请输入正整数*/}>
                    <Icon type="question-circle-o" />
                </Tooltip>
              </span>
              )}>
                {getFieldDecorator('timeLimit', {
                  rules: [
                    {
                      validator: (item, value, callback) => {
                        if(value < 0){
                          callback(messages('credit-setting.key81')/*请输入正整数*/)
                        }
                        if(value === 0){
                          callback(messages('credit-setting.key81')/*请输入正整数*/)
                        }
                        if(value && isNaN(value) && value !== 0 && value !== ''){
                          callback(messages('credit-setting.key81')/*请输入正整数*/)
                        }
                        callback();
                      }
                    }
                  ],
                  initialValue: nowData.id ? nowData['timeLimit'] : undefined
                })(
                  <InputNumber min={0} precision={0}/>
                )}
              </FormItem>
            </div>
          )}
          <FormItem {...formItemLayout} label={messages('credit-setting.key100')/*规则项编码*/}>
            {getFieldDecorator('ruleConditionCode', {
              rules: [
                {
                  required: true,
                  message: messages('common.please.enter')
                },
              ]
            })(
              <Input maxLength="100" disabled={!!nowData.id || ruleTypeId === 1001}/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('common.remark')/*备注*/}>
            {getFieldDecorator('comment')(
              <TextArea autosize={{minRows: 2}}
                        maxLength="500"
                        style={{minWidth:'100%'}}
                        placeholder={messages('common.please.enter')/*请输入*/}/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('credit-setting.key41')/*处理类型*/}>
            {getFieldDecorator('operationType', {
              rules: [
                {
                  required: true,
                  message: messages('common.please.select')
                }
              ]
            })(
              <Select onChange={this.handleChangeOperationType}>
                {constants.creditRuleOperation.map(item => <Option key={item.value} value={item.value}>{item.text}</Option>)}
              </Select>
            )}
          </FormItem>
          {this.renderChange()}
          {ruleTypeId === 1002 && (
            <FormItem {...formItemLayout} label={messages('credit-setting.key40')/*关联意见*/}>
              {getFieldDecorator('creditRelationDTOList', {
                rules: [
                  {
                    required: false,
                    message: messages('common.please.select')
                  },
                ]
              })(
                <Chooser selectorItem={this.replySelectorItem}
                         valueKey="id"
                         labelKey="reply"
                         showNumber
                         listExtraParams={nowData.id ? {conditionId: nowData.id} : {}}/>
              )}
            </FormItem>
          )}
          {ruleTypeId === 1003 && nowData.id && (
            <FormItem {...formItemLayout} label={messages('credit-setting.key117')/*提醒规则*/}>
              <Popover
                content={(nowData.creditTaskDTOList || []).map(item => item.content).join('；')}
                overlayStyle={{ maxWidth: 400 }}
              >
                <Input disabled={true} value={(nowData.creditTaskDTOList || []).map(item => item.content).join('；')}/>
              </Popover>
            </FormItem>
          )}
          <FormItem {...formItemLayout} label={messages('common.column.status')/*状态*/}>
            {getFieldDecorator('valid',{
              initialValue: true,
              valuePropName: 'checked'
            })(
              <Switch/>
            )}
          </FormItem>
          <div className="slide-footer">
            <Button type="primary" htmlType="submit" loading={loading}>{messages('common.save')/* 保存 */}</Button>
            <Button onClick={this.onCancel}>{messages('common.cancel')/* 取消 */}</Button>
          </div>
        </Form>
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {
    company: state.login.company,
    creditModel: state.creditSetting.creditModel
  }
}
const WrappedNewCreditModelRule = Form.create()(NewCreditModelRule);

export default connect(mapStateToProps)(WrappedNewCreditModelRule);
